package com.lvxh.exp.expuser.controller;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lvxh.exp.bean.BaseController;
import com.lvxh.exp.bean.GridResultHolder;
import com.lvxh.exp.expmenu.dao.holder.Expmenu;
import com.lvxh.exp.expmenu.service.ExpmenuService;
import com.lvxh.exp.expuser.dao.holder.Expuser;
import com.lvxh.exp.expuser.service.ExpuserService;
import com.lvxh.exp.filter.global.Constant;
import com.lvxh.exp.utils.ExpSecurity;

@RequestMapping("/expuser")
@Controller
public class ExpuserController extends BaseController
{
    private static final Logger log = Logger.getLogger(ExpuserController.class);

    @Autowired
    private ExpuserService expuserService;

    @Autowired(required = true)
    private ExpmenuService menuService;

    @RequestMapping("/explogin")
    public ModelAndView login(Expuser user, String validateCode)
    {
        log.info("start method initExpuser");
        Map<String, String> map = new HashMap<String, String>();
        if (validateCode != null
                && (validateCode.toUpperCase(Locale.getDefault())).equals(getSession().getAttribute(
                        Constant.VERIFICATION_CODE)))
        {

            if (user.getLoginname() == null || "".equals(user.getLoginname()))
            {
                map.put("errorMessage", "User Name or Password  Error");
                log.info("end method initExpuser");
                return new ModelAndView("expuser/login", map);
            }
            else
            {
                String password = ExpSecurity.encrypt(Constant.SHA_256,
                        user.getLoginname() + user.getPassword());
                user.setPassword(password);
                List<Expuser> userList = expuserService.getList(user);
                if (userList != null && userList.size() == 1)
                {
                    Expmenu menu = new Expmenu();
                    List<Expmenu> list = menuService.getList(menu);
                    getSession().setAttribute("menuList", list);
                    getSession().setAttribute("nativid", 1);
                    getSession().setAttribute(Constant.AUTH_EXP_USER, userList.get(0));
                    return new ModelAndView("expuser/redirectPage");

                }
                else
                {
                    map.put("errorMessage", "User Name or Password  Error");
                    log.info("end method initExpuser");
                    return new ModelAndView("expuser/login", map);
                }
            }
        }
        else
        {
            map.put("errorMessage", "Validate Code Error");
            log.info("end method initExpuser");
            return new ModelAndView("expuser/login", map);
        }

    }

    @RequestMapping("/initexpuser")
    public ModelAndView initExpuser()
    {
        log.info("start method initExpuser");
        log.info("end method initExpuser");
        return new ModelAndView("expuser/viewExpuser");
    }

    @RequestMapping("/getGrid")
    @ResponseBody
    public GridResultHolder getGrid(Expuser bean)
    {
        log.info("start method getGrid");
        GridResultHolder result = new GridResultHolder();
        int count = expuserService.getCountOfSummary(bean);
        int sum = procesPage(bean, count);
        result.setResult(expuserService.getListOfSummary(bean));
        result.setPageCount(sum);
        log.info("end method getGrid");
        return result;
    }

    @RequestMapping("/initadd")
    public ModelAndView initAdd()
    {
        log.info("start method initAdd");
        log.info("end method initAdd");
        return new ModelAndView("expuser/addExpuser");
    }

    @RequestMapping("/add")
    public ModelAndView add(Expuser bean)
    {
        int result = 0;
        log.info("start method add");
        Map<String, String> map = new HashMap<String, String>();
        bean.setCreatetime(new Date(System.currentTimeMillis()));
        Expuser loginUser = (Expuser) getSession().getAttribute(
                Constant.AUTH_EXP_USER);
        bean.setPassword(ExpSecurity.encrypt(Constant.SHA_256,
                bean.getLoginname() + bean.getPassword()));
        bean.setCreatetime(new Date(System.currentTimeMillis()));
        if (loginUser == null)
        {
            bean.setCreateuserid(-1);

        }
        else
        {
            bean.setCreateuserid(loginUser.getId());
        }
        try
        {
            result = expuserService.insert(bean);
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
        if (result > 0)
        {
            map.put("backUrl", "/expuser/initexpuser.action");
            log.info("end method add");
            return new ModelAndView("global/success", map);
        }
        else
        {
            log.info("end method add");
            return new ModelAndView("global/failed");
        }

    }

    @RequestMapping("/initmodify")
    public ModelAndView initModify(String delFlag)
    {
        log.info("start method initModify");
        Map<String, Object> map = new HashMap<String, Object>();
        Expuser bean = new Expuser();
        bean.setId(Integer.parseInt(delFlag));
        List<Expuser> list = expuserService.getList(bean);
        if (list == null || list.isEmpty())
        {
            log.info("end method initModify");
            return new ModelAndView("global/failed");
        }
        else
        {
            map.put("bean", list.get(0));
            log.info("end method initModify");
            return new ModelAndView("expuser/modifyExpuser", map);
        }
    }

    @RequestMapping("/modify")
    public ModelAndView modify(Expuser bean)
    {
        int result = 0;
        log.info("start method modify");
        Map<String, String> map = new HashMap<String, String>();

        try
        {
            result = expuserService.update(bean);
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
        if (result > 0)
        {
            map.put("backUrl", "/expuser/initexpuser.action");
            log.info("end method modify");
            return new ModelAndView("global/success", map);
        }
        else
        {
            log.info("end method modify");
            return new ModelAndView("global/failed");
        }

    }

    @RequestMapping("/del")
    public ModelAndView del(String delFlag)
    {
        int result = 0;
        log.info("start method modify");
        Map<String, String> map = new HashMap<String, String>();

        try
        {
            if (delFlag != null && !"".equals(delFlag))
            {
                Expuser bean = new Expuser();
                bean.setId(Integer.parseInt(delFlag.split("\\|")[1]));
                result = expuserService.delete(bean);
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
        if (result > 0)
        {
            map.put("backUrl", "/expuser/initexpuser.action");
            log.info("end method modify");
            return new ModelAndView("global/success", map);
        }
        else
        {
            log.info("end method modify");
            return new ModelAndView("global/failed");
        }

    }

    @RequestMapping("/delall")
    public ModelAndView delAll(String delFlag)
    {

        int result = 0;
        log.info("start method modify");
        Map<String, String> map = new HashMap<String, String>();

        try
        {
            if (delFlag != null && !"".equals(delFlag))
            {

                List<Expuser> list = new ArrayList<Expuser>();
                String str[] = delFlag.split("\\|");
                for (int i = 1; i < str.length; i++)
                {
                    Expuser bean = new Expuser();
                    bean.setId(Integer.parseInt(str[i]));
                    list.add(bean);
                }
                result = expuserService.delete(list);
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
        if (result > 0)
        {
            map.put("backUrl", "/expuser/initexpuser.action");
            log.info("end method modify");
            return new ModelAndView("global/success", map);
        }
        else
        {
            log.info("end method modify");
            return new ModelAndView("global/failed");
        }

    }
    @RequestMapping("/main")
    public ModelAndView dologin(Integer nativid)
    {
        log.debug("start method  doLogin");
        if (nativid == null)
        {
            nativid = 1;
        }
        @SuppressWarnings("unchecked")
        List<Expmenu> list = (List<Expmenu>) getSession().getAttribute(
                "menuList");
        getSession().setAttribute("menuList", list);
        getSession().setAttribute("nativid", nativid);

        if(1 == nativid)
        {
            return new ModelAndView("expuser/welcome");
            
        }
        else
        {
            return new ModelAndView("expmemo/viewExpmemo");
        }

    }

    @RequestMapping("/setMenuParam")
    @ResponseBody
    public GridResultHolder setMenuParam(String menuid,String parentmenuid)
    {
        log.info("start method getGrid");
        GridResultHolder result = new GridResultHolder();
        getSession().setAttribute("menuid", menuid);
        getSession().setAttribute("parentmenuid", parentmenuid);
        log.info("end method getGrid");
        return result;
    }
    
    @RequestMapping("/explogout")
    public ModelAndView logout()
    {
        log.info("start method initExpuser");
        getSession().invalidate();
        log.info("end method initExpuser");
        return new ModelAndView("expuser/login");
        
    }


}
